package com.steven.treatment_nurse.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;

import com.alibaba.fastjson.JSONObject;
import com.steven.treatment_nurse.R;
import com.steven.treatment_nurse.entity.HSBedEntity;
import com.steven.treatment_nurse.entity.ResultEntity;
import com.steven.treatment_nurse.net.MyCallback;
import com.steven.treatment_nurse.net.TaskNoHead;
import com.steven.treatment_nurse.utils.SPUtils;
import com.steven.treatment_nurse.utils.ToastUtils;
import com.videogo.errorlayer.ErrorInfo;
import com.videogo.openapi.EZConstants;
import com.videogo.openapi.EZOpenSDK;
import com.videogo.openapi.EZPlayer;
import com.videogo.realplay.RealPlayMsg;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Response;

@SuppressLint("ValidFragment")
public class MonitFragment extends LazyLoadBaseFragment {
    @BindView(R.id.btn_speak)
    Button btn_speak;


    private Handler mHandler;
    private SurfaceView mSurface;
    private EZPlayer ezpCamera;
    private EZPlayer ezpTalk;
    private HSBedEntity hsBedEntity;
    private static String TAG = MonitFragment.class.getSimpleName();

    private String accessToken;
    private String deviceserial;
    private String validatecode;

    private static boolean isOpenCamera = false;
    private boolean isSpeaking = false;

    @OnClick({R.id.btn_speak
    })
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_speak://说话
                if (isOpenCamera) {
                    isSpeaking = !isSpeaking;
                    speakToCamera(isSpeaking);
                    if (isSpeaking) {
                        btn_speak.setText("关闭语音");
                    } else {
                        btn_speak.setText("开启语音");
                    }
                } else {
                    ToastUtils.showToast(getActivity(), "摄像头初始化中，稍后再试！");
                }
                break;
        }
    }

    @Override
    protected int getLayoutRes() {
        return R.layout.fragment_monit;
    }

    public MonitFragment(HSBedEntity hsBedEntity) {
        this.hsBedEntity = hsBedEntity;
    }

    @Override
    protected void initView(View rootView, Bundle s) {
        mHandler = new MyHandler();
        mSurface = rootView.findViewById(R.id.surFace);
    }

    @Override
    protected void requestData() {
        super.requestData();
        Log.e(TAG, "requestData: refreshData");
    }

    @Override
    protected void stopRefresh() {
        super.stopRefresh();
        if (ezpCamera != null) {
            ezpCamera.stopRealPlay();
            ezpCamera.stopVoiceTalk();
            ezpCamera.release();
            ezpCamera = null;
        }
    }

    private void getData() {
        String token = SPUtils.get(getActivity(), "token", "") + "";
        TaskNoHead.getInstance().getDevice(token, hsBedEntity.getId()).enqueue(new MyCallback<ResultEntity>() {
            @Override
            protected void onSuccess(Response response) {
                try {
                    JSONObject jsonObject = (JSONObject) JSONObject.toJSON(response.body());
                    assert jsonObject != null;
                    if (jsonObject.getInteger("code") == 0) {
                        JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                        accessToken = jsonObject1.getString("accessToken");
                        deviceserial = jsonObject1.getString("deviceserial");
                        validatecode = jsonObject1.getString("validatecode");
                        setData();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }

    @Override
    protected void requestDataAutoRefresh() {
        super.requestDataAutoRefresh();
        Log.e(TAG, "requestData: requestDataAutoRefresh");
        getData();
    }

    //初始化摄像头
    private void setData() {
        EZOpenSDK.getInstance().setAccessToken(accessToken);//设置accessToken
        initCamera();
        initTalk();
    }


    //静态内部类handler，防止内存泄漏
    private static class MyHandler extends Handler {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case EZConstants.EZRealPlayConstants.MSG_REALPLAY_PLAY_SUCCESS:
                    //播放成功
                    isOpenCamera = true;
                    break;
                case EZConstants.EZRealPlayConstants.MSG_REALPLAY_PLAY_FAIL:
                    //播放失败,得到失败信息
                    ErrorInfo errorinfo = (ErrorInfo) msg.obj;
                    //得到播放失败错误码
                    int code = errorinfo.errorCode;
                    //得到播放失败模块错误码
                    String codeStr = errorinfo.moduleCode;
                    //得到播放失败描述
                    String errorDescription = errorinfo.description;
                    //得到播放失败解决方方案
                    String errorScheme = errorinfo.sulution;
                    break;
                case EZConstants.MSG_VIDEO_SIZE_CHANGED:
                    //解析出视频画面分辨率回调
                    try {
                        String temp = (String) msg.obj;
                        String[] strings = temp.split(":");
                        int mVideoWidth = Integer.parseInt(strings[0]);
                        int mVideoHeight = Integer.parseInt(strings[1]);
                        //解析出视频分辨率
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case RealPlayMsg.MSG_REALPLAY_VOICETALK_SUCCESS://对讲开启成功
                    Log.e(TAG, "handleMessage: 对讲开启成功");
                    break;
                case RealPlayMsg.MSG_REALPLAY_VOICETALK_FAIL://失败
                    ErrorInfo errorinfo_1 = (ErrorInfo) msg.obj;
                    //得到播放失败错误码
                    int code1 = errorinfo_1.errorCode;
                    Log.e(TAG, "handleMessage: "+code1);

                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 调起摄像头  开启直播
     */
    private void initCamera() {

        ezpCamera = EZOpenSDK.getInstance().createPlayer(deviceserial, 1);
        //设置Handler, 该handler将被用于从播放器向handler传递消息
        ezpCamera.setHandler(mHandler);

        //设置播放器的显示Surface
        ezpCamera.setSurfaceHold(mSurface.getHolder());


        /**
         * 设备加密的需要传入密码
         * 传入视频加密密码，用于加密视频的解码，该接口可以在收到ERROR_INNER_VERIFYCODE_NEED或ERROR_INNER_VERIFYCODE_ERROR错误回调时调用
         * @param verifyCode 视频加密密码，默认为设备的6位验证码
         */
        ezpCamera.setPlayVerifyCode(validatecode);

        //开启直播
        ezpCamera.startRealPlay();
    }

    //初始化对讲
    private void initTalk() {
        ezpTalk = EZOpenSDK.getInstance().createPlayer(deviceserial, 1);
        //设置Handler, 该handler将被用于从播放器向handler传递消息
        /**
         * 设备加密的需要传入密码
         * 传入视频加密密码，用于加密视频的解码，该接口可以在收到ERROR_INNER_VERIFYCODE_NEED或ERROR_INNER_VERIFYCODE_ERROR错误回调时调用
         * @param verifyCode 视频加密密码，默认为设备的6验证码
         */
        ezpTalk.setPlayVerifyCode(validatecode);
    }

    /**
     * @param isToTalk 设备说还是  手机端说  true：手机端说
     * @param isOpen   是否开启关闭对讲
     */
    private void speakToCamera( boolean isOpen) {
        if (isOpen) {
            //开启对讲
            ezpTalk.setHandler(mHandler);
            ezpCamera.closeSound();
            ezpTalk.startVoiceTalk();
        } else {
            try{
                ezpTalk.stopVoiceTalk();
                ezpCamera.openSound();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        //设备端听，手机端说
//        ezpTalk.setVoiceTalkStatus(true);
    }

}
